/**
 * @author : andy
 * @description : 权限相关
 */
import { defineStore } from "pinia";
import type { AccessMenuItem } from "./types";
import type { RouteRecordRaw } from "vue-router";
import { findTreeNodeByValue } from "@/utils/tree";
export interface AccessState {
  /** 权限菜单 */
  accessMenus: AccessMenuItem[];
  /** 权限路由 */
  accessRoutes: RouteRecordRaw[];
  /** 是否已经检查过权限 */
  isAccessChecked: boolean;
  /** 使用mixed-nav模式下的侧边栏菜单 */
  mixedSidebarMenus: AccessMenuItem[];
  /** 选中的菜单项 */
  selectedMenuKeys: string[];
  /** 内嵌菜单 */
  iframeMenus: AccessMenuItem[];
  /** 需要缓存的页面 */
  keepAlivePages: string[];
  /** 二级菜单 */
  secondMenus: AccessMenuItem[];
}
export const useAccessStore = defineStore('access' , {
  state : (): AccessState => ({
    accessMenus : [],
    accessRoutes : [],
    isAccessChecked : false,
    mixedSidebarMenus : [],
    selectedMenuKeys : [],
    iframeMenus : [],
    keepAlivePages : [],
    secondMenus : []
  }),
  actions : {
    setAccessMenus (menus: AccessMenuItem[]) {
      this.accessMenus = menus;
    },
    setAccessRoutes (routes: RouteRecordRaw[]) {
      this.accessRoutes = routes;
    },
    setIsAccessChecked (checked: boolean) {
      this.isAccessChecked = checked;
    },
    setMixedSidebarMenusByCode (code: string) {
      const current = findTreeNodeByValue(this.accessMenus , 'code' , code , {childProps : 'children'});
      this.mixedSidebarMenus = current ? current.children || [] : [];
    },
    setSecondMenusByCode (code: string) {
      const current = this.accessMenus.filter(item => item.code === code)[0];
      this.secondMenus = current ? current.children || [] : [];
    },
    setSelectedMenuKeys (key: string) {
      this.selectedMenuKeys = [key];
    },
    setIframeMenus (menus: AccessMenuItem[]) {
      this.iframeMenus = menus;
    },
    addKeepAlivePages (name: string) {
      this.keepAlivePages.push(name);
    },
    clearKeepAlivePages () {
      this.keepAlivePages = [];
    },
    hasKeepAlivePage (name: string) {
      return this.keepAlivePages.includes(name);
    }
  }
})